package com.pachong.android.framework.httprequest.responsecallbacks;


import android.content.Context;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;

import com.pachong.android.baseuicomponent.CompState;
import com.pachong.android.baseuicomponent.ILoadable;
import com.pachong.android.baseuicomponent.LoadState;
import com.pachong.android.baseuicomponent.activity.RecyclerViewBaseActivity;
import com.pachong.android.baseuicomponent.fragment.RecyclerViewBaseFragment;
import com.pachong.android.baseuicomponent.refreshable.IRefreshable;
import com.pachong.android.framework.httprequest.IResponseDataParser;
import com.pachong.android.framework.httprequest.ResponseParser;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;


/**
 * 自动处理数据请求后UI的变化
 * <p>
 * 只针对List格式的数据
 *
 * @param <E>
 */
public class ListDataRequestListener<E> extends RequestListener<E> {

    private static final String INTERNAL_SERVER_ERROR = "REST/INTERNAL_SERVER_ERROR";
    public static final int ERR_CODE_INVALID_NET = -1;//  网路异常，可能断开了or其他情况
    public static final int ERR_CODE_PARSE = -2;  // 解析异常， 服务器返回的数据非json格式
    public static final int ERR_CODE_INTERNAL_SERVER = -3;  // 数据异常：服务端返回具体的error msg，客户端自己判断给用户统一的展示

    private static final String ERR_STR_INVALID_NET = "网络不可用，请检查网络";
    private static final String ERR_STR_PARSE = "数据解析异常";
    private static final String ERR_STR_INTERNAL_SERVER = "未知错误";



    private RecyclerViewBaseActivity mActContext;
    private RecyclerViewBaseFragment mFragContext;
    private IRefreshable mRefreshable;
    // 每次刷新都先清空数据
    private boolean mClearData = false;


    /**
     * 使用默认的数据解析器
     *
     * @param context
     * @param clazz
     */
    public ListDataRequestListener(RecyclerViewBaseActivity context, Class clazz) {
        super(new ResponseParser<E>(clazz));
        mActContext = context;
        if (context instanceof IRefreshable) {
            mRefreshable = (IRefreshable) context;
        }
    }


    /**
     * 使用默认的数据解析器
     *
     * @param context
     * @param clazz
     */
    public ListDataRequestListener(RecyclerViewBaseFragment context, Class clazz) {
        super(new ResponseParser<E>(clazz));
        mFragContext = context;
        if (context instanceof IRefreshable) {
            mRefreshable = (IRefreshable) context;
        }
    }


    public ListDataRequestListener(RecyclerViewBaseActivity context, @NonNull IResponseDataParser dataParser) {
        super(dataParser);
        mActContext = context;
        if (context instanceof IRefreshable) {
            mRefreshable = (IRefreshable) context;
        }
    }

    public ListDataRequestListener(RecyclerViewBaseFragment context, @NonNull IResponseDataParser dataParser) {
        super(dataParser);
        mFragContext = context;
        if (context instanceof IRefreshable) {
            mRefreshable = (IRefreshable) context;

        }
    }


    /**
     *
     * @param context
     * @param clazz
     * @param clearData  每次刷新都清除原先的数据
     */
    public ListDataRequestListener(RecyclerViewBaseActivity context, Class clazz, boolean clearData) {
        this(context, clazz);
        mClearData = clearData;
    }

    public ListDataRequestListener(RecyclerViewBaseFragment context, Class clazz, boolean clearData) {
        this(context, clazz);
        mClearData = clearData;
    }

    @Override
    public void onStart(Context context, String url) {
        //下拉刷新的时候不要出现刷新图标
       if(mClearData==false){
           Log.e("12121212","sdasdsad");
           mFragContext.setState(CompState.DATA);
       }
    }



    @Override
    public void onSuccess(Object listData) {
        List<E> list = (List<E>)listData;
        if (mFragContext != null) {
            // Framgent
            updateFragmentViews(list);
        } else if (mActContext != null) {
            // Activity
            updateActivityViews(list);
        } else {
            return;
        }
    }

    @Override
    public void onFailure(Throwable t, int errorNo, String strMsg) {
        if (mFragContext != null) {
            // Fragment
            mFragContext.setState(CompState.EMPTY_ERROR);
        } else if (mActContext != null) {
            // Activity
            mActContext.setState(CompState.EMPTY_ERROR);
        } else {
            return;
        }
    }

    public void onDeliverFailureResponse(Throwable t, int errCode, String errStr) {
        String errMsg;

        // errCode == -1 值是从父类返回
        if (errCode == -1 && TextUtils.isEmpty(errStr)) {
            // 没有网络
            errMsg = ERR_STR_INVALID_NET;
            errCode = ERR_CODE_INVALID_NET;

        } else {
            // 解析从服务器返回的数据
            try {
                JSONObject jobj = new JSONObject(errStr);
                String code = jobj.optString("code");
                String message = jobj.optString("message");

                if (!TextUtils.isEmpty(code) && !TextUtils.isEmpty(message)) {
                    if (errCode == 400) {
                        errMsg = message;
                    } else if(errCode == 403) {
                        errMsg = "授权失败";
                    } else {
                        if (TextUtils.isEmpty(message)) {
                            message = ERR_STR_INTERNAL_SERVER;
                        }
                        errMsg = message;
                    }

                } else {
                    errMsg = ERR_STR_PARSE;
                    errCode = ERR_CODE_PARSE;
                    Log.w("Http", "解析异常， error code 或者 error message 为空");
                }

            } catch (JSONException e) {
                e.printStackTrace();
                // 解析异常， 服务器返回的数据非json格式
                errMsg = ERR_STR_PARSE;
                errCode = ERR_CODE_PARSE;
                Log.w("Http", "解析异常， 服务器返回的数据非json格式");
            }
        }
        onFailure(t, errCode, errMsg);
    }



    private void updateFragmentViews(List<E> list) {
        if (mClearData) {
            mRefreshable.hideRefreshView();
            mFragContext.getAdapter().getData().clear();
            mFragContext.getAdapter().notifyDataSetChanged();
        }
        if (list != null && list.size() > 0) {
            mFragContext.getAdapter().getData().addAll(list);
            mFragContext.getAdapter().notifyItemInserted(mFragContext.getAdapter().getData().size());
            mFragContext.setState(CompState.DATA);

        }
        updateViews(mFragContext);
    }


    private void updateActivityViews(List<E> list) {
        if (mClearData) {
            mActContext.getAdapter().getData().clear();
            mActContext.getAdapter().notifyDataSetChanged();
        }
        if (list != null && list.size() > 0) {
            mActContext.getAdapter().getData().addAll(list);
            mActContext.getAdapter().notifyItemInserted(mActContext.getAdapter().getData().size());
            mActContext.setState(CompState.DATA);
        }
        updateViews(mActContext);
    }


    public void updateViews(ILoadable actContext) {
        if (getResponseDataParser().hasMore()) {
            actContext.changeLoadState(LoadState.IDLE);
        } else {
            actContext.changeLoadState(LoadState.FINISH);
        }
        if (mRefreshable != null) {
            mRefreshable.hideRefreshView();
        }
    }




}
